package com.project;

import com.project.servlet.AddServlet;
import com.project.servlet.FirstServlet;
import com.project.servlet.StudentServlet;
import com.project.servlet.UserServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Service;

import javax.servlet.Servlet;


public class MainServlet {
    private ApplicationContext springContext = new AnnotationConfigApplicationContext(MybatisConfig.class);

    public MainServlet() {
        //创建tomcat对象
        Tomcat tomcat = new Tomcat();
        //设施启动端口
        tomcat.setPort(8088);
        //引导http引擎
        tomcat.getConnector();
        //创建上下文
        Context context = tomcat.addContext("",null);
        try {
//            this.registerServlet(context,FirstServlet.class,"/fir");
            this.registerServlet(context,StudentServlet.class,"*.do");
            this.registerServlet(context, AddServlet.class,"/add");
//            Wrapper servlet = Tomcat.addServlet(context,"User",springContext.getBean(UserServlet.class));
//            servlet.setLoadOnStartup(1);
//            servlet.addMapping("/findAll");
            //启动tomcat
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void registerServlet(Context context, Class servletClass, String urlPath) throws Exception {
        //注册servlet
        //第一个参数为上下文对象，第二个为servlet名称，第三个参数为servlet实现类对象
        Wrapper servlet = Tomcat.addServlet(context,
                servletClass.getSimpleName(), (Servlet)servletClass.newInstance());
        //容器启动就直接实例化servlet
        servlet.setLoadOnStartup(1);
        //配置servlet的请求路径
        servlet.addMapping(urlPath);
    }

    public static void main(String[] args) {
        new MainServlet();
    }
}
